package com.qmerak.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.qmerak.common.SysConstants;

/**
 * @author shaohong.cheng
 * @date 2013-4-7
 */
public class AuthorityFilter implements Filter {
	private String LOGIN_PAGE = "/jsp/login.jsp";

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpSession session = request.getSession();

		String contenxtPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.substring(contenxtPath.length());

		// 静态资源
		if (uri.startsWith("/js/") || uri.startsWith("/css/")
				|| uri.startsWith("/images/")) {
			arg2.doFilter(arg0, arg1);
			return;
		}
		// 首页及登录界面
		if (uri.equals("/") || uri.equals("index.jsp")
				|| uri.equals(LOGIN_PAGE)) {
			arg2.doFilter(arg0, arg1);
			return;
		}
		// 身份验证
		if (uri.equals("/member/login")) {
			String userName = request.getParameter("loginName");
			if (userName != null) {
				arg2.doFilter(arg0, arg1);
				return;
			}
		}
		// 是否已经通过身份验证
		if (session.getAttribute(SysConstants.SYS_LOGIN_USER) == null) {
			request.getRequestDispatcher(LOGIN_PAGE).forward(arg0, arg1);
		} else {
			arg2.doFilter(arg0, arg1);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
